﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Mysoft.App.Appservices.Basic;
using Mysoft.Common.Enum;
using Mysoft.Tasks.Queue.IService;

namespace Mysoft.App.Appservices
{
    /// <summary>
    /// Rabbitmq
    /// </summary>
    public class MQAppService:AppServiceBase
    {
        private readonly IMQEventBus _eventBus;


     
        /// <summary>
        /// 
        /// </summary>
        /// <param name="eventBus"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public MQAppService(IMQEventBus eventBus)
        {
            _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
        }

        /// <summary>
        /// 推送消息
        /// </summary>
        /// <returns>消费信息在控制台体现</returns>
        [HttpPost, AllowAnonymous]
        public JsonResult Publish()
        {

            string s = $"推送时间：{DateTime.Now}";
            _eventBus.Publish(new
            {
                Body = s,
            }, exchange: "RabbitMQ.EventBus.Test", routingKey: "RabbitMQ.EventBus.Test");
            return Success(s);
        }

        /// <summary>
        /// 推送延时消息
        /// </summary>
        /// <param name="delay">秒</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelayedPublish(int delay)
        {
            string s = $"推送延时消息,推送时间：{DateTime.Now}";
            _eventBus.DelayedPublish(
                    message: new { Body = s, },
                    queue: "RabbitMQ.DelayedEvent",          //延时队列
                    exchange: "RabbitMQ.DelayedEvent",       //延时交换机
                    routingKey: "RabbitMQ.DelayedEvent",     //延时路由
                    deadExchange: "RabbitMQ.EventBus.Test",  //死信交换机
                    deadRoutingKey: "RabbitMQ.EventBus.Test",//死信路由
                    QueryType: DeadQueryType.message,        //延时队列模式
                    delay: 1000 * delay                      //延时时间(毫秒)

            );
            return Success(s);
        }
        /// <summary>
        /// redis推送
        /// </summary>
        /// <returns></returns>
        [HttpPost,HttpGet]
        public JsonResult RedisPublish() 
        {

            _CacheContext.LPush("p_message", "这是一条消息");
            var message = _CacheContext.ListDequeue("p_message");
            var message1 = _CacheContext.ListDequeue("p_message");
            message = message.ToString() + message1.ToString();
            return Success(message);
        }

        /// <summary>
        /// 获取消息队列中间件
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public JsonResult GetMode() 
        {
            return Success(_eventBus.GetMode());
        }
    }
}
